package org.example.netty.test.nio.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * @author zp
 * @version 1.0
 * @description: 双向通信的客户端
 * @date 2023/3/25 15:32
 */
@Slf4j
public class CommunicationClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.group(workerGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel ch) {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(new LoggingHandler(LogLevel.DEBUG));
                    pipeline.addLast(new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) {
                            log.info("连接服务器成功");
                            ByteBuf buffer = ctx.alloc().buffer(20);
                            buffer.writeBytes("hello server".getBytes());
                            ctx.writeAndFlush(buffer);
                            // 释放ByteBuf 因为后续没有对象使用 自己就是头尾节点 默认会自动释放 无需手动释放
                            // buffer.release();
                        }

                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) {
                            if (msg instanceof ByteBuf) {
                                ByteBuf message = (ByteBuf) msg;
                                log.info("服务器发送的消息 [{}]", message.toString(Charset.defaultCharset()));
                                message.release();
                            }
                        }
                    });

                }
            });
            ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress("127.0.0.1", 8899));
            channelFuture.channel().closeFuture().addListener((ChannelFutureListener) future -> {
                log.info("客户端关闭");
                workerGroup.shutdownGracefully();
            });
        } catch (Exception e) {
            log.error("客户端异常", e);
        }
    }
}
